<script setup lang="ts">
import type { ItemType } from 'ant-design-vue';
import { useAsyncRouteStore } from '@/stores/async-routes';

import { useRouter } from 'vue-router';

import { buildMenuTree } from './helper';

defineOptions({
  name: 'LayoutSlider',
});

const props = defineProps<Props>();
interface Props {
  /**
   * 是否折叠
   */
  collapsed: boolean;
}

const selectedKeys = ref<string[]>([]);
const openKeys = ref<string[]>([]);
const menus = ref<ItemType[]>([]);
const router = useRouter();

const asyncRouteStore = useAsyncRouteStore();
menus.value = buildMenuTree(asyncRouteStore.menus);

function initializeMenuSelection(menu: ItemType) {
  if (menu && 'children' in menu && isArray(menu.children) && !isEmpty(menu.children)) {
    const children = menu.children as ItemType[];
    openKeys.value.push(menu.key as string);
    selectedKeys.value.push(children[0].key as string);
    router.push({ name: children[0].key as string });
  }
}
const firstMenu = menus.value[0];
initializeMenuSelection(firstMenu);

function onMenuClick(item: ItemType) {
  selectedKeys.value.push(item.key as string);
  router.push({
    name: item.key as string,
  });
}
</script>

<template>
  <ALayoutSider :collapsed="props.collapsed" :trigger="null" theme="dark" collapsible width="240">
    <div class="py-2 flex justify-center items-center gap-x-2 border-b border-b-gray-600">
      <img src="@/assets/icons/logo.svg " width="36" height="36" />
      <span v-if="!collapsed" class="whitespace-nowrap font-bold text-lg text-white">管理系统</span>
    </div>
    <AMenu v-model:selected-keys="selectedKeys" :open-keys="openKeys" mode="inline" theme="dark" :items="menus" @click="onMenuClick" />
  </ALayoutSider>
</template>
